<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :model-value="visible"
      title="产品特性配置对比项选择"
      width="1110px"
      draggable
      destroy-on-close
      align-center
      @close="closeDialog"
      class="maxhDialog"
    >
      <el-row :gutter="10">
        <!-- 用户列表 -->
        <el-col :span="24">
          <!-- <div class="search-container" style="padding: 18px 15px 0"> -->
          <el-form
            :model="searchParam"
            :inline="true"
            label-width="68px"
            label-position="left"
          >
            <SearchFormGroup
              :data="searchParam"
              @change-search="handleSearchChange"
              @change-gageEquipCode="changeEquipCode"
            />
            <!-- <el-form-item label="检具名称">
              <el-select
                v-model="searchParam.gageEquipMarkCode"
                placeholder="请选择检具名称"
                clearable
                filterable
              >
                <el-option
                  v-for="item in gageEquipList"
                  :key="item.toolCode"
                  :label="item.toolName"
                  :value="item.toolCode"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item label="特性名称">
              <el-select
                v-model="searchParam.paramId"
                placeholder="请选择特性名称"
                clearable
                filterable
                :filter-method="customFilter5"
                :disabled="!canSelectSpecific"
                @change="search"
              >
                <el-option
                  v-for="item in filteredOptions5"
                  :key="item.id"
                  :label="item.paramName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="reset"><i-ep-refresh />重置</el-button>
            </el-form-item>
          </el-form>
          <!-- </div> -->

          <!-- <el-card
            shadow="never"
            class="table-container card-table-p15 h-[536px]"
          > -->
          <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="tableData"
            :key="Math.random"
            @select="handleSelectionChange"
            @select-all="handleAllChange"
            class="card-table"
            border
            height="460px"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="工段"
              prop="workshopSectionCode"
              min-width="80"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="工序"
              prop="processCode"
              min-width="80"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="生产线"
              prop="equipCode"
              min-width="80"
              align="center"
              show-overflow-tooltip
            />
            <!-- <el-table-column
              label="项目描述"
              prop="projectName"
              min-width="80"
              align="center"
              show-overflow-tooltip
            /> -->
            <el-table-column
              label="型号描述"
              prop="modelName"
              min-width="80"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品型号"
              prop="modelCode"
              min-width="80"
              align="center"
              show-overflow-tooltip
            />
            <!-- <el-table-column
              label="检具设备"
              prop="gageEquipMarkName"
              min-width="80"
              align="center"
              show-overflow-tooltip
            /> -->
            <el-table-column
              label="检具类别"
              prop="groupCode"
              min-width="80"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="特性名称"
              prop="paramName"
              min-width="160"
              align="left"
              show-overflow-tooltip
            />
            <el-table-column
              label="公称尺寸"
              prop="parameterStandards"
              min-width="75"
              show-overflow-tooltip
              align="right"
            />
            <el-table-column
              label="公差下限"
              prop="lowerLimitValue"
              min-width="75"
              show-overflow-tooltip
              align="right"
            />
            <el-table-column
              label="公差上限"
              prop="upperLimitValue"
              min-width="75"
              show-overflow-tooltip
              align="right"
            />
            <el-table-column
              label="预警工单"
              min-width="75"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                <el-tag v-if="handleCheckAllChange1(scope.row)" type="success">
                  是
                </el-tag>
                <el-tag v-else type="info"> 否</el-tag>
              </template>
            </el-table-column>

            <el-table-column
              label="预警邮件"
              min-width="75"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                <el-tag v-if="handleCheckAllChange2(scope.row)" type="success">
                  是
                </el-tag>
                <el-tag v-else type="info"> 否</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="特性状态"
              min-width="75"
              show-overflow-tooltip
              align="right"
            >
              <template #default="scope"> {{ "" }} </template>
            </el-table-column>
          </el-table>

          <el-pagination
            small
            background
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 25, 50, 100]"
            :total="pageable.total"
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-[20px]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <!-- </el-card> -->
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import { ElTable } from "element-plus";
import dayjs from "dayjs";
import request from "@/utils/request";
import {
  getMdminspectiontoolApi,
  getMdmProcessEquipApi,
  getMdmProcessProjectApi,
  getMdmproductinfosApi,
  getMdmprojectinfosApi,
  getSpecificListApi,
  getMdmprocessListApi,
  getMdmProcessEquipApi1,
  getMdminspectionGroupApi,
} from "@/utils/commonData";
import SearchFormGroup from "@/views/pcm/pcmMonitoring/components/SearchFormGroup1.vue";
import { deepClone } from "@/utils/commonHooks";
import _ from "lodash-es";

defineOptions({
  name: "PcmmeasurefeaturesContrastSelect",
  inheritAttrs: false,
});

interface SelectOption {
  id?: string;
}
const emit = defineEmits(["update:visible", "echo-info"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Array,
    default: () => {
      return [];
    },
  },
  isMultiple: {
    type: Boolean,
    default: true,
  },
});

const { visible, isMultiple } = toRefs(props);

// 深层拷贝
function deepCopy(val: any) {
  return JSON.parse(JSON.stringify(val));
}

// 表格选择
const totalMultipleSelection: any = ref([]);
// 表格触发全选
function handleAllChange(selecteds: any) {
  if (isMultiple.value) {
    const currentSelection = deepCopy(totalMultipleSelection.value);
    const ids = deepCopy(totalMultipleIds.value);
    if (selecteds.length) {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.id);
        if (indexId < 0) {
          totalMultipleSelection.value.push(item);
        }
      });
    } else {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.id);
        if (indexId > -1) {
          currentSelection.splice(indexId, 1);
          ids.splice(indexId, 1);
        }
      });
      totalMultipleSelection.value = currentSelection;
    }
  } else {
    delAll();
    ElMessage.warning("单选，请重新选择");
  }
}
// 表格触发单个选择
function handleSelectionChange(val: any, row: SelectOption) {
  let addOptions = false;
  val?.map((item: SelectOption) => {
    if (item.id === row.id) {
      addOptions = true;
    }
  });
  if (!addOptions) {
    const index = totalMultipleIds.value.indexOf(row.id);
    totalMultipleSelection.value.splice(index, 1);
  } else {
    if (isMultiple.value) {
      totalMultipleSelection.value.push(row);
    } else {
      delAll();
      multipleTable.value?.toggleRowSelection(row, true);
      totalMultipleSelection.value = [row];
    }
  }
}

// 右侧人员选择操作
const multipleTable = ref(ElTable);
// 全部清除
function delAll() {
  totalMultipleSelection.value = [];
  multipleTable.value.clearSelection();
}
// 单个删除
function delSingle(current: SelectOption, index: number) {
  totalMultipleSelection.value.splice(index, 1);
  tableData.value.map((item: SelectOption) => {
    if (item.id === current.id) {
      multipleTable.value?.toggleRowSelection(item, false);
    }
  });
}

/** 弹窗展开 初始化数据 */
const totalMultipleIds: any = ref([]);
watch(
  () => totalMultipleSelection,
  async (newVal: any) => {
    const ids: any = [];
    newVal.value?.map((item: SelectOption) => ids.push(item.id));
    totalMultipleIds.value = ids;
  },
  { deep: true }
);

// 请求参数
// const requestApi = "/dmpDosPcm/pcmmeasurefeatures/queryByPage";
const requestApi = "/dmpDosPcm/pcmmeasurefeaturesgroup/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({});

// 初始化搜索参数数据
const searchParamInit = {
  // 工段
  workshopSectionId: "",
  workshopSectionCode: "",
  // 项目
  // projectCode: "",
  // projectId: "",
  // 工序
  processCode: "",
  processId: "",
  // 设备
  equipCode: "",
  equipId: "",
  // 产品型号
  productCode: "",
  productId: "",
  // 检具类型
  gageEquipToolKind: "",
  // 检具名称
  gageEquipCode: "",
  // 机器号
  gageEquipMarkCode: "",
  // 特性
  paramId: "",
  toolGroupId: "",
};

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
function dataCallBack(data: any) {
  setTimeout(() => {
    data.map((item: SelectOption) => {
      if (totalMultipleIds.value.includes(item.id)) {
        multipleTable.value?.toggleRowSelection(item, true);
      }
    });
  }, 0);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  loading,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError
);

onMounted(() => {
  getTableList();
  //获取量检具列表
  getGageEquipList({});
  getGageEquipList1("");
});

/** 弹窗展开 初始化数据 */
const oldTotalSelection: any = ref([]);
watch(
  () => props.visible,
  async (newVal: boolean) => {
    if (newVal) {
      totalMultipleSelection.value = deepCopy(props.data);
      oldTotalSelection.value = deepCopy(props.data);
      dataCallBack(tableData.value);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  totalMultipleSelection.value = oldTotalSelection.value;
  dataCallBack(tableData.value);
  emit("update:visible", false);
}

/** 确定提交 */
async function handleSubmit() {
  if (!isMultiple.value && totalMultipleSelection.value.length > 1) {
    ElMessage.error("请选择");
  } else {
    emit("update:visible", false);
    emit("echo-info", totalMultipleSelection.value);
  }
}

// 组件销毁时调用
onBeforeUnmount(() => {
  emit("update:visible", false);
  closeDialog();
});

// 处理传回数据
const handleSearchChange = (data) => {
  Object.assign(searchParam.value, data);
  // 可执行字段相关的特定逻辑
  if (searchParam.value?.gageEquipCode) {
    searchParam.value.toolGroupId = oldGageEquipList1.value.filter(
      (item) => item.groupCode == searchParam.value.gageEquipCode
    )[0].id;
  } else {
    searchParam.value.toolGroupId = "";
  }
};

const oldGageEquipList1 = ref<any>([]);
async function getGageEquipList1(type: string) {
  oldGageEquipList1.value = (await getMdminspectionGroupApi({})) || [];
}

// --------------------------------------------------------------------------------------------------------组件 结束

// 间距变化
const changeEquipCode = (id: string) => {
  if (id) {
    searchParam.paramId = "";
  }
};
// 获取量检具列表
const gageEquipList = ref<any>([]);

async function getGageEquipList(params) {
  gageEquipList.value = (await getMdminspectiontoolApi({})) || [];
}

// 获取特性值列表
const specificList = ref<any>([]);

async function getSpecificList() {
  specificList.value =
    (await getSpecificListApi({
      equipId: searchParam.value.equipId,
      toolGroupId: searchParam.value.toolGroupId,
      modelId: searchParam.value.productId,
      processId: searchParam.value.processId,
    })) || [];
  filteredOptions5.value = deepClone(specificList.value);
}
const filteredOptions5 = ref([]);
// 使用 debounce 包装过滤方法
const customFilter5 = _.debounce((query) => {
  if (!query) {
    filteredOptions5.value = [...specificList.value];
    return;
  }
  filteredOptions5.value = specificList.value.filter((option: any) =>
    option.paramName.toLowerCase().includes(query.toLowerCase())
  );
}, 300);
// 检测必填项，筛选特性值列表
const canSelectSpecific = ref(false);
watch(
  () => searchParam.value,
  (newVal) => {
    if (
      newVal.equipCode &&
      newVal.gageEquipCode &&
      newVal.productCode &&
      newVal.processCode
    ) {
      canSelectSpecific.value = true;
      getSpecificList();
    } else {
      searchParam.value.paramId = "";
      canSelectSpecific.value = false;
      specificList.value = [];
      filteredOptions5.value = [];
    }
    searchParam.value.gageEquipMarkCode = newVal.gageEquipCode;
  },
  {
    deep: true,
  }
);

// 预警工单 回显
function handleCheckAllChange1(formData: any) {
  if (
    formData.isSingleOrder == 0 &&
    formData.isAverageOrder == 0 &&
    formData.isLongOrder == 0 &&
    formData.isStageOrder == 0 &&
    formData.isFeaturesOrder == 0
  ) {
    return false;
  } else {
    return true;
  }
}

// 预警邮件 回显
function handleCheckAllChange2(formData: any) {
  if (
    formData.isSingle == 0 &&
    formData.isAverage == 0 &&
    formData.isLong == 0 &&
    formData.isStage == 0 &&
    formData.isFeatures == 0
  ) {
    return false;
  } else {
    return true;
  }
}
</script>

<style lang="scss" scoped>
:deep(.maxhDialog .el-dialog__body) {
  overflow-y: auto;
  padding: 20px 20px 2px;
  .mini-search {
    padding: 8px 12px;
  }
  .el-card__body {
    padding: 15px;
  }
  .el-select {
    width: 175px;
    margin-right: 14px;
  }
  .el-table--default .cell {
    padding: 0 7px;
  }
  .el-table__empty-block {
    min-height: 200px;
  }
}
// :deep(.el-dialog__body) {
//   padding-bottom: 0px !important;
//   padding-top: 15px !important;
// }
.name:hover {
  background-color: rgb(236, 245, 255) !important;
  color: var(--el-menu-active-color) !important;
  border-radius: 6px;
  svg {
    color: var(--el-menu-active-color) !important;
  }
}
.name svg {
  cursor: pointer;
}
:deep(.el-form--inline .el-form-item) {
  margin-right: 10px;
  margin-bottom: 14px;
}
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color))
    inset !important;
}
.el-button svg {
  margin-right: 0;
}
.card-table-p15 {
  :deep(.el-dialog__body) {
    padding: 15px;
  }
  .card-table {
    line-height: normal;
  }
}

:deep(.el-tree) {
  height: 533px;
}
</style>
